from typing import Dict

from fastapi import APIRouter,Depends,Query
from datetime import date, timedelta
from sqlalchemy.orm import Session

from ..database.db import get_db
from ..crud.user_crud import get_user_quantity
from ..crud.textbook_crud import get_textbook_quantity
from ..crud.paper_crud import get_paper_quantity
from ..crud.video_crud import get_video_quantity
from ..crud.image_crud import get_images_quantity
from ..crud.voice_crud import get_voice_quentity
from ..crud.ppt_crud import get_ppt_quentity
from ..crud.usage_crud import get_usage_by_date,get_usage_by_date_range
from ..crud.user_crud import get_user_by_data
from ..crud.usage_crud import get_questions_quantity

from ..schemas.base import ResponseModel
from ..utils.jwt_handler import get_username
from pydantic import BaseModel

from ..schemas.base import ResponseModel
icon_router = APIRouter(prefix="/draw-ico", tags=["制图"])



class FourIcons(BaseModel):
    user_quantity:int
    tradtition_quantity:int
    ai_create_quantity:int
    total_quantity:int



class FourIconsResponseModel(ResponseModel):
    data: FourIcons

@icon_router.post("/resource-library",response_model=FourIconsResponseModel)
async def get_icons(db: Session = Depends(get_db),
                    username: str = Depends(get_username)):
    """
    ## 获取资源库中课本和试卷的数量
    **第一行四个块**
    """
    user_quantity = get_user_quantity(db)

    textbook_quantity = get_textbook_quantity(db)
    paper_quantity = get_paper_quantity(db)
    tradtition_quantity = textbook_quantity + paper_quantity

    video_quantity = get_video_quantity(db)
    image_quantity = get_images_quantity(db)
    voice_quantity = get_voice_quentity(db)
    ppt_quantity = get_ppt_quentity(db)
    ai_create_quantity = video_quantity + image_quantity + voice_quantity + ppt_quantity

    total_quantity = ai_create_quantity + tradtition_quantity
    return {
        "code": 200,
        "data": {
            "user_quantity": user_quantity,
            "tradtition_quantity": tradtition_quantity,
            "ai_create_quantity": ai_create_quantity,
            "total_quantity": total_quantity
        },
        "message": "获取成功"
    }

class AiCreate(BaseModel):
    video_quantity:int
    image_quantity:int
    voice_quantity:int
    ppt_quantity:int
    questions_quantity:int



class AiCreateResponseModel(ResponseModel):
    data: AiCreate
@icon_router.post("/ai-create",response_model=AiCreateResponseModel)
async def get_ai_create_icons(db: Session = Depends(get_db),
                    username: str = Depends(get_username)):
    """
    Ai总共生成各类资源的数量
    **雷达图**
    """
    video_quantity = get_video_quantity(db)
    image_quantity = get_images_quantity(db)
    voice_quantity = get_voice_quentity(db)
    ppt_quantity = get_ppt_quentity(db)

    questions_quantity = get_questions_quantity(db)

    return {
        "code": 200,
        "data": {
            "video_quantity": video_quantity,
            "image_quantity": image_quantity,
            "voice_quantity": voice_quantity,
            "ppt_quantity": ppt_quantity,
            "questions_quantity":questions_quantity,
        },
        "message":"ok"
    }

class TraditionResource(BaseModel):
    textbook_quantity:int
    paper_quantity:int



class TraditionResourceResponseModel(ResponseModel):
    data: TraditionResource
@icon_router.post("/contrast",response_model=TraditionResourceResponseModel)
async def get_contrast_icons(db: Session = Depends(get_db),
                    username: str = Depends(get_username)):
    """
    对比图标
    **对比图或者扇形图**
    """
    textbook_quantity = get_textbook_quantity(db)
    paper_quantity = get_paper_quantity(db)
    total_quantity = textbook_quantity + paper_quantity
    return {
        "code": 200,
        "data": {
            "textbook_quantity":textbook_quantity,
            "paper_quantity":paper_quantity,
        },
        "message":"ok"
    }

@icon_router.post("/get-data",response_model=AiCreateResponseModel)
async def get_resource_library_icons(
        data: date = Query(..., description="查询日期"),
        db: Session = Depends(get_db),
        username: str = Depends(get_username)):
    """
    ## 单日使用情况
    - data: 日期（右上角传入）
    **右侧柱状图**
    """
    usage_list=get_usage_by_date(db,data)

    data={
            "video_quantity": 0,
            "image_quantity": 0,
            "voice_quantity": 0,
            "ppt_quantity": 0,
            "questions_quantity":0,
        }
    if not usage_list:
        return{
            "code":200,
            "data":data,
            "message":"ok"
        }
    for usage in usage_list:
        data["video_quantity"]+=usage["video_quantity"]
        data["image_quantity"]+=usage["image_quantity"]
        data["voice_quantity"]+=usage["voice_quantity"]
        data["ppt_quantity"]+usage["ppt_quantity"]
        data["questions_quantity"]+=usage["questions_quantity"]
    return{
        "code":200,
        "data":data,
        "message":"ok"
    }


class RecentIconsDemo(ResponseModel):
    data: Dict[str, AiCreate]


@icon_router.post("/recent", response_model=RecentIconsDemo)
async def get_recent_icons(
        db: Session = Depends(get_db),
        username: str = Depends(get_username)):
    # 获取当前日期
    current_date = date.today()
    # 获取七天前的日期
    start_date = current_date - timedelta(days=7)

    # 查询最近七天的数据
    usage_list = get_usage_by_date_range(db, start_date, current_date)

    # 按日期分组并统计各类资源数量
    recent_data: Dict[date, Dict[str, int]] = {}

    for usage in usage_list:
        # 使用 data 字段作为日期键
        usage_date = usage["data"]
        if usage_date not in recent_data:
            recent_data[usage_date] = {
                "video_quantity": 0,
                "image_quantity": 0,
                "voice_quantity": 0,
                "ppt_quantity": 0,
                "questions_quantity": 0
            }

        # 累加各类资源数量
        recent_data[usage_date]["video_quantity"] += usage['video_quantity'] or 0
        recent_data[usage_date]["image_quantity"] += usage['image_quantity'] or 0
        recent_data[usage_date]["voice_quantity"] += usage['voice_quantity'] or 0
        recent_data[usage_date]["ppt_quantity"] += usage['ppt_quantity'] or 0
        recent_data[usage_date]["questions_quantity"] += usage['questions_quantity'] or 0

    # 将结果转换为按日期排序的列表，并适配 AiCreate 模型
    sorted_dates = sorted(recent_data.keys())
    result_data = {}
    for date_str in sorted_dates:
        date_key = date_str.strftime("%Y-%m-%d")
        result_data[date_key] = {
            "video_quantity": recent_data[date_str]["video_quantity"],
            "image_quantity": recent_data[date_str]["image_quantity"],
            "voice_quantity": recent_data[date_str]["voice_quantity"],
            "ppt_quantity": recent_data[date_str]["ppt_quantity"],
            "questions_quantity": recent_data[date_str]["questions_quantity"]
        }

    return {
        "code": 200,
        "data": result_data,
        "message": "ok"
    }